package com.study.lxy.classloader;

import sun.misc.FloatConsts;
import sun.misc.Launcher;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;

public class MyClassLoader extends ClassLoader {


    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
        try {
            System.out.println("filename = " + fileName);
            InputStream is = getClass().getResourceAsStream(fileName);
            if(is == null){
                return super.loadClass(name);
            }
            byte[] b = new byte[is.available()];
            is.read(b);
            return defineClass(name, b, 0, b.length);
        } catch (IOException e){
            throw new ClassNotFoundException();
        }
    }

    @Override
    public String toString() {
        return "MyClassLoader{.......}";
    }

    public static void main(String[] args) throws Exception {
        MyClassLoader loader = new MyClassLoader();
        Object o = loader.loadClass("com.study.lxy.classloader.MyClassLoader").newInstance();
        MyClassLoader loader2 = new MyClassLoader();
        Object o2 = loader2.loadClass("com.study.lxy.classloader.MyClassLoader").newInstance();

        System.out.println(o);
        System.out.println(o.toString());
        System.out.println(loader.getParent());
        System.out.println(loader.getParent().getParent());
        System.out.println(loader.getParent().getParent().getParent());

        System.out.println(o instanceof MyClassLoader);
        System.out.println(o.getClass().equals(o2.getClass()));

        System.out.println(loader.getClass().equals(loader2.getClass()));
    }
}
